<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="10" animated />
            </div>
            <div v-else class="idle-details-container">
                <div class="details-header">
                    <div class="details-header-user-info">
                        <el-image
                                style="width: 80px; height: 80px; border-radius: 5px; display: flex; align-items: center; justify-content: center;"
                                :src="userInfo.avatarUrl"
                                fit="contain">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-user-solid" style="font-size: 50px;"></i>
                            </div>
                        </el-image>
                        <div style="margin-left: 10px;">
                            <div class="details-header-user-info-nickname">
                                商家: {{userInfo.nickname}}
                                <el-button 
                                    v-if="!isMaster" 
                                    size="mini" 
                                    :type="isFollowing ? 'info' : 'primary'"
                                    plain
                                    @click="followButton"
                                    style="margin-left: 10px;">
                                    {{isFollowing ? '已关注' : '关注商家'}}
                                </el-button>
                            </div>
                            <div class="details-header-user-info-time">{{productInfo.createdAt}} 发布</div>
                        </div>
                    </div>
                    <div class="details-header-buy" :style="'width:'+(isMaster?'150px;':'280px;')">
                        <div v-if="!isMaster && productInfo.statusSold !== 'ON_SALE'" style="color: red;font-size: 16px;">
                            商品已{{productInfo.statusSold === 'SOLD' ? '售出' : '下架'}}
                        </div>
                        <el-button v-if="isMaster && productInfo.statusSold === 'ON_SALE'" type="danger" @click="changeStatus('OFF_SALE')" plain>下架</el-button>
                        <el-button v-if="isMaster && productInfo.statusSold === 'OFF_SALE'" type="primary" @click="changeStatus('ON_SALE')" plain>重新上架</el-button>
                    </div>
                </div>

                <div class="details-info">
                    <div class="details-info-title">{{productInfo.productName || '未知商品'}}</div>
                    <div class="product-price-actions">
                        <div class="price-tag">
                            <span class="price-symbol">￥</span>
                            <span class="price-value">{{productInfo.productPrice || 0}}</span>
                        </div>
                        <div class="action-area" v-if="!isMaster && productInfo.statusSold === 'ON_SALE'">
                            <div class="product-stats">
                                <span class="favorite-count">
                                    <i class="el-icon-star-on" :style="{ color: isFavorite ? '#409EFF' : '#909399' }"></i>
                                    <span>收藏 {{productInfo.favoriteCount || 0}}</span>
                                </span>
                                <span class="view-count">
                                    <i class="el-icon-view"></i>
                                    <span>浏览 {{productInfo.viewCount || 0}}</span>
                                </span>
                            </div>
                            <div class="action-buttons">
                                <el-button type="danger" @click="buyButton">立即购买</el-button>
                                <el-button 
                                    :type="isFavorite ? 'warning' : 'primary'" 
                                    :icon="isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'"
                                    plain 
                                    @click="favoriteButton">
                                    {{isFavorite ? '已收藏' : '收藏'}}
                                </el-button>
                                <el-button 
                                    type="primary" 
                                    icon="el-icon-chat-dot-round"
                                    plain 
                                    @click="startChat"
                                    v-if="!isMaster && productInfo.statusSold === 'ON_SALE'">
                                    私聊
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <div class="details-info-main" v-html="formattedDescription">
                    </div>
                    <div v-if="productInfo.images && productInfo.images.length > 0" class="details-picture">
                        <div class="image-grid">
                            <div v-for="(imgUrl,i) in productInfo.images" :key="i" class="image-wrapper">
                                <el-image 
                                    class="product-image"
                                    :src="imgUrl.trim()"
                                    fit="contain"
                                    :preview-src-list="productInfo.images"
                                    @error="handleImageError(i)"
                                    v-show="!imageErrors[i]">
                                    <div slot="error" class="image-slot">
                                        <i class="el-icon-picture-outline"></i>
                                    </div>
                                </el-image>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'

    export default {
        name: "product-details",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                productInfo:{
                    productID: '',
                    productName: '',
                    productDescription: '',
                    images: [],
                    productPrice: 0,
                    productCategory: '',
                    statusSold: '',
                    statusCheck: '',
                    createdAt: '',
                    userId: '',
                    favoriteCount: 0,
                    messageCount: 0,
                    viewCount: 0
                },
                userInfo: {
                    nickname: '',
                    avatarUrl: ''
                },
                isMaster: false,
                isFavorite: false,
                isFollowing: false,
                loading: true,
                imageErrors: {}
            };
        },
        computed: {
            formattedDescription() {
                if (!this.productInfo.productDescription) return '';
                const lines = this.productInfo.productDescription.split(/\r?\n/);
                return lines.map(line => `<p>${line}</p>`).join('');
            }
        },
        created() {
            const productId = this.$route.query.productId;
            if (!productId) {
                this.$message.error('商品ID不存在');
                return;
            }

            console.log('加载商品ID:', productId);
            this.loading = true;

            // 加载商品信息
            this.$api.getProductDetail(productId).then(res => {
                console.log('商品详情:', res);
                if (res.code === 200) {
                    this.productInfo = res.data;
                    // 处理图片数据
                    if (typeof this.productInfo.images === 'string') {
                        this.productInfo.images = this.productInfo.images.split(',').filter(url => url.trim() !== '');
                    } else if (!Array.isArray(this.productInfo.images)) {
                        this.productInfo.images = [];
                    }
                    console.log('处理后的图片数组:', this.productInfo.images);
                    
                    // 获取用户信息
                    if (this.productInfo.userId) {
                        this.loadUserInfo(this.productInfo.userId);
                    } else {
                        console.error('商品所属者ID不存在');
                        this.userInfo = {
                            nickname: '未知用户',
                            avatarUrl: ''
                        };
                    }
                    
                    // 检查是否是商品所有者
                    const currentUser = JSON.parse(localStorage.getItem('userInfo') || '{}');
                    this.isMaster = currentUser.id === this.productInfo.userId;
                    
                    // 检查收藏状态
                    this.checkFavorite();
                    // 检查关注状态
                    this.checkFollowStatus();
                } else {
                    this.$message.error(res.message || '加载商品信息失败');
                }
            }).catch(err => {
                console.error('加载商品失败:', err);
                this.$message.error('111网络错误，请稍后重试');
            }).finally(() => {
                this.loading = false;
            });
        },
        methods: {
            // 加载用户信息
            loadUserInfo(userId) {
                // 检查是否已登录
                const token = localStorage.getItem('token');
                console.log('正在获取用户信息，用户ID:', userId);
                console.log('当前token状态:', token ? '已存在' : '不存在');
                
                if (!token) {
                    console.error('未登录，无法获取用户信息');
                    this.$message.warning('请先登录后查看卖家信息');
                    this.userInfo = {
                        nickname: '未知用户',
                        avatarUrl: ''
                    };
                    return;
                }

                this.$api.getUserDetail(userId).then(res => {
                    console.log('获取用户信息响应:', res);
                    if (res.code === 200 && res.data) {
                        this.userInfo = {
                            nickname: res.data.nickname || res.data.username || '未知用户',
                            avatarUrl: res.data.avatar || ''
                        };
                        console.log('用户信息设置成功:', this.userInfo);
                    } else {
                        console.error('获取用户信息失败:', res.message);
                        this.$message.error(res.message || '获取用户信息失败');
                        this.userInfo = {
                            nickname: '未知用户',
                            avatarUrl: ''
                        };
                        if (res.code === 401) {
                            console.error('Token验证失败，需要重新登录');
                            this.$message.error('登录已过期，请重新登录');
                            // this.$router.push('/login');
                        }
                    }
                }).catch(err => {
                    console.error('获取用户信息请求失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                    this.userInfo = {
                        nickname: '未知用户',
                        avatarUrl: ''
                    };
                });
            },
            // 检查收藏状态
            checkFavorite() {
                // 检查用户是否已登录
                const token = localStorage.getItem('token');
                if (!token) {
                    console.log('用户未登录，跳过收藏状态检查');
                    this.isFavorite = false;
                    return;
                }

                // 检查是否是商品所有者，所有者不能收藏自己的商品
                if (this.isMaster) {
                    console.log('商品所有者不能收藏自己的商品');
                    this.isFavorite = false;
                    return;
                }

                this.$api.checkFavorite(this.productInfo.productID).then(res => {
                    console.log('检查收藏状态响应:', res);
                    if (res.code === 200 && res.data !== undefined) {
                        // 后端返回的是布尔值，直接使用
                        this.isFavorite = Boolean(res.data);
                        console.log('当前收藏状态:', this.isFavorite);
                    } else if (res.code === 401) {
                        // Token过期或无效
                        console.log('用户认证失效，设置收藏状态为false');
                        this.isFavorite = false;
                        // 可以选择性地提示用户重新登录
                        // this.$message.warning('登录已过期，请重新登录');
                    } else {
                        console.error('检查收藏状态失败:', res.message || '未知错误');
                        this.isFavorite = false;
                    }
                }).catch(err => {
                    console.error('检查收藏状态请求失败:', err);
                    // 网络错误或其他异常情况
                    this.isFavorite = false;
                    if (err.response && err.response.status === 401) {
                        console.log('认证失败，可能需要重新登录');
                    }
                });
            },
            // 检查关注状态
            checkFollowStatus() {
                // 检查用户是否已登录
                const token = localStorage.getItem('token');
                if (!token) {
                    console.log('用户未登录，跳过关注状态检查');
                    this.isFollowing = false;
                    return;
                }

                // 检查是否是商品所有者，所有者不能关注自己
                if (this.isMaster) {
                    console.log('不能关注自己');
                    this.isFollowing = false;
                    return;
                }

                this.$api.checkFollow(this.productInfo.userId).then(res => {
                    console.log('检查关注状态响应:', res);
                    if (res.code === 200 && res.data !== undefined) {
                        this.isFollowing = Boolean(res.data);
                        console.log('当前关注状态:', this.isFollowing);
                    } else if (res.code === 401) {
                        console.log('用户认证失效，设置关注状态为false');
                        this.isFollowing = false;
                    } else {
                        console.error('检查关注状态失败:', res.message || '未知错误');
                        this.isFollowing = false;
                    }
                }).catch(err => {
                    console.error('检查关注状态请求失败:', err);
                    this.isFollowing = false;
                });
            },
            
            // 更改商品状态（上架/下架）
            changeStatus(status) {
                this.$api.updateProductStatus({
                    productId: this.productInfo.productID,
                    status: status
                }).then(res => {
                    if (res.code === 200) {
                        this.productInfo.statusSold = status;
                        this.$message.success(status === 'ON_SALE' ? '商品已上架' : '商品已下架');
                    } else {
                        this.$message.error(res.message || '操作失败');
                    }
                }).catch(err => {
                    console.error('更改商品状态失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            },

            buyButton() {
                // 1. 校验登录状态
                const token = localStorage.getItem('token');
                if (!token) {
                    this.$message.warning('请先登录');
                    this.$router.push('/login');
                    return;
                }

                // 1.1 获取当前用户ID
                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                let currentUserId = null;
                
                // 如果localStorage中没有用户信息，尝试从token中获取
                if (!userInfo || !userInfo.id) {
                    try {
                        // JWT token的格式是 header.payload.signature
                        const payload = JSON.parse(atob(token.split('.')[1]));
                        currentUserId = Number(payload.sub); // sub 是 JWT 中存储用户ID的字段
                    } catch (e) {
                        console.error('解析token失败:', e);
                        this.$message.error('获取用户信息失败，请重新登录');
                        return;
                    }
                } else {
                    currentUserId = Number(userInfo.id);
                }

                // 1.2 检查是否是商品卖家
                const sellerId = Number(this.productInfo.userId);
                console.log('当前用户ID:', currentUserId, '卖家ID:', sellerId);
                
                if (currentUserId === sellerId) {
                    this.$message.warning('您不能购买您自己的商品');
                    return;
                }

                // 2. 获取地址信息
                const addressData = this.addressData || [];
                let selectedAddress = addressData.find(addr => addr.defaultFlag) || null;

                // 3. 尝试从localStorage获取默认地址
                if (!selectedAddress) {
                    const localAddrStr = localStorage.getItem('defaultAddress');
                    if (localAddrStr) {
                        try {
                            selectedAddress = JSON.parse(localAddrStr);
                        } catch {
                            selectedAddress = null;
                        }
                    }
                }

                // 4. 如果还是没有默认地址，取第一个地址
                if (!selectedAddress && addressData.length > 0) {
                    selectedAddress = addressData[0];
                }

                // 5. 地址存在性校验
                if (!selectedAddress) {
                    this.$message.error('请先添加收货地址');
                    this.eidtAddress = true; // 打开地址编辑页面
                    return;
                }

                // 6. 地址字段完整性校验
                const requiredFields = [
                    'consigneeName',
                    'consigneePhone',
                    'provinceName',
                    'cityName',
                    'regionName',
                    'detailAddress'
                ];

                const missingFields = [];
                requiredFields.forEach(field => {
                    if (!selectedAddress[field]) {
                        missingFields.push(this.getFieldLabel(field));
                    }
                });

                if (missingFields.length > 0) {
                    this.$message.error(`请完善以下地址信息：${missingFields.join('、')}`);
                    this.eidtAddress = true;
                    return;
                }

                // 7. 电话格式校验
                if (!/^1[3-9]\d{9}$/.test(selectedAddress.consigneePhone)) {
                    this.$message.error('请输入正确的手机号码');
                    return;
                }

                // 8. 购买数量校验
                const quantity = this.orderQuantity || 1;
                if (quantity <= 0) {
                    this.$message.error('购买数量必须大于0');
                    return;
                }

                // 9. 创建订单
                this.$api.createOrder({
                    productId: this.productInfo.productID,
                    quantity: quantity,
                    consigneeName: selectedAddress.consigneeName,
                    consigneePhone: selectedAddress.consigneePhone,
                    province: selectedAddress.provinceName,
                    city: selectedAddress.cityName,
                    district: selectedAddress.regionName,
                    detailAddress: selectedAddress.detailAddress,
                    postalCode: selectedAddress.postalCode || '000000',
                    defaultFlag: selectedAddress.defaultFlag,
                    images: this.productInfo.images||[]
                }).then(res => {
                    if (res.code === 200) {
                        // 创建订单成功后直接跳转到订单页面
                        this.$router.push({
                            path: '/order',
                            query: { id: res.data.orderId }
                        });
                    } else {
                        this.$message.error(res.message || '创建订单失败');
                    }
                }).catch(err => {
                    console.error('创建订单失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            },


            // 收藏/取消收藏
            favoriteButton() {
                // 检查登录状态
                const token = localStorage.getItem('token');
                if (!token) {
                    this.$message.warning('请先登录后再收藏');
                    return;
                }

                const api = this.isFavorite ? 'deleteFavorite' : 'addFavorite';
                this.$api[api](this.productInfo.productID).then(res => {
                    if (res.code === 200) {
                        this.isFavorite = !this.isFavorite;
                        // 更新收藏数
                        this.productInfo.favoriteCount += this.isFavorite ? 1 : -1;
                        this.$message({
                            type: 'success',
                            message: this.isFavorite ? '收藏成功' : '已取消收藏',
                            duration: 1500
                        });
                    } else {
                        this.$message.error(res.message || '操作失败');
                    }
                }).catch(err => {
                    console.error('收藏操作失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            },
            
            // 关注/取消关注
            followButton() {
                // 检查登录状态
                const token = localStorage.getItem('token');
                if (!token) {
                    this.$message.warning('请先登录后再关注');
                    return;
                }

                const api = this.isFollowing ? 'unfollowUser' : 'followUser';
                this.$api[api](this.productInfo.userId).then(res => {
                    if (res.code === 200) {
                        this.isFollowing = !this.isFollowing;
                        this.$message({
                            type: 'success',
                            message: this.isFollowing ? '关注成功' : '已取消关注',
                            duration: 1500
                        });
                    } else {
                        this.$message.error(res.message || '操作失败');
                    }
                }).catch(err => {
                    console.error('关注操作失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            },
            
            // 处理图片加载失败
            handleImageError(index) {
                this.$set(this.imageErrors, index, true);
            },
            
            startChat() {
                // 检查是否登录
                const token = localStorage.getItem('token');
                if (!token) {
                    this.$message.warning('请先登录');
                    this.$router.push('/login');
                    return;
                }

                // 检查是否是商品所有者
                if (this.isMaster) {
                    this.$message.warning('不能与自己聊天');
                    return;
                }

                // 检查商品状态
                if (this.productInfo.statusSold !== 'ON_SALE') {
                    this.$message.warning('商品已下架或售出，无法发起聊天');
                    return;
                }

                // 创建聊天会话
                this.$api.startChat({
                    productId: this.productInfo.productID,
                    initialMessage: '你好，我对这个商品感兴趣'
                }).then(res => {
                    if (res.code === 200) {
                        // 跳转到聊天页面
                        this.$router.push({
                            path: '/chat',
                            query: {
                                chatId: res.data.id,
                                sellerId: this.productInfo.userId,
                                productId: this.productInfo.productID,
                                productName: this.productInfo.productName
                            }
                        });
                    } else {
                        this.$message.error(res.message || '开启聊天失败');
                    }
                }).catch(err => {
                    console.error('开启聊天失败:', err);
                    if (err.response && err.response.status === 401) {
                        this.$message.error('登录已过期，请重新登录');
                        this.$router.push('/login');
                    } else {
                        this.$message.error('网络错误，请稍后重试');
                    }
                });
            }
        }
    }
</script>

<style scoped>
    .idle-details-container {
        min-height: 85vh;
    }

    .details-header {
        height: 80px;
        border-bottom: 10px solid #f6f6f6;
        display: flex;
        justify-content: space-between;
        padding: 20px;
        align-items: center;
    }

    .details-header-user-info {
        display: flex;
    }

    .details-header-user-info-nickname {
        font-weight: 600;
        font-size: 18px;
        margin-bottom: 10px;
    }

    .details-header-user-info-time {
        font-size: 12px;
        color: #555555;
    }

    .details-header-buy {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 50px;
        width: 280px;
        flex-wrap: wrap;
        gap: 10px;
    }

    .details-info {
        padding: 20px 50px;
    }

    .details-info-title {
        font-size: 22px;
        font-weight: 600;
        margin-bottom: 10px;
    }

    .details-info-main {
        font-size: 17px;
        color: #121212;
        line-height: 160%;
    }

    .details-picture {
        margin: 20px auto;
        padding: 0 20px;
        max-width: 1200px;
        width: 100%;
    }

    .image-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 20px;
        justify-content: center;
    }

    .image-wrapper {
        position: relative;
        width: 100%;
        padding-top: 100%;
    }

    .product-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border: 1px solid #DCDFE6;
        border-radius: 4px;
        overflow: hidden;
        background-color: #f8f9fa;
    }

    .product-image :deep(.el-image__inner) {
        width: 100%;
        height: 100%;
        object-fit: contain;
        transition: transform 0.3s ease;
    }

    .product-image:hover :deep(.el-image__inner) {
        transform: scale(1.05);
    }

    .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
    }

    .image-slot i {
        font-size: 30px;
    }

    .loading-container {
        padding: 20px;
        min-height: 85vh;
    }

    .product-price-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 0;
        border-bottom: 1px solid #f0f0f0;
        margin-bottom: 20px;
    }

    .price-tag {
        display: flex;
        align-items: baseline;
    }

    .price-symbol {
        color: #ff4d4f;
        font-size: 18px;
        margin-right: 2px;
    }

    .price-value {
        color: #ff4d4f;
        font-size: 28px;
        font-weight: 600;
    }

    .action-area {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    .product-stats {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 20px;
        font-size: 14px;
        color: #909399;
    }

    .favorite-count, .view-count {
        display: flex;
        align-items: center;
        gap: 4px;
    }

    .favorite-count i, .view-count i {
        font-size: 16px;
        margin-right: 2px;
    }

    .action-buttons {
        display: flex;
        gap: 15px;
    }

    .action-buttons .el-button {
        padding: 12px 25px;
        font-size: 16px;
    }

    @media screen and (max-width: 768px) {
        .image-grid {
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
        }
        
        .details-picture {
            padding: 0 10px;
        }
    }
</style>